package com.itzb.asone.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.itzb.asone.application.AppContext;
import com.itzb.asone.application.Application;
import com.itzb.asone.application.ApplicationResourceInfo;
import com.itzb.asone.application.ApplicationUserInfo;
import com.itzb.asone.constant.SystemConstant;

public class AppContextFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String requestURI = httpRequest.getRequestURI();
		String headURI = httpRequest.getContextPath();

		ApplicationUserInfo userInSession = (ApplicationUserInfo) httpRequest.getSession().getAttribute(SystemConstant.USER_INFO);
		if (userInSession != null){

			ApplicationResourceInfo ari = (ApplicationResourceInfo) httpRequest.getSession().getAttribute(SystemConstant.USER_RESOURCE);
			ari.setBreadcrumb(AppContext.getBreadcrumb(userInSession.getUserId(),headURI,requestURI));
			if(ari.getPageTitle()==null)ari.setPageTitle(AppContext.getPageTitle());
			Map<String,String> head = new HashMap<String, String>();
			head = ari.getBreadcrumb().get(ari.getBreadcrumb().size()-1);
			ari.setHead(head);
			httpRequest.getSession().setAttribute(SystemConstant.USER_RESOURCE,ari);
			Application.setApplicationInfo(userInSession);
		}
		chain.doFilter(request, response);
	}
	public void destroy() {
		
	}
}
